/*
 * @Author: shiguo
 * @Date: 2021-04-27 10:38:04
 * @LastEditors: shiguo
 * @LastEditTime: 2022-09-09 10:58:34
 * @FilePath: /@aks-dev/easyui/lib/Hud/Toast/Toast.tsx
 */
import React, { useImperativeHandle, useState, useRef } from 'react';
import { View, StyleSheet, Text, Dimensions, Animated, Easing } from 'react-native';


import type { ToastOptions } from '.'

const errorMsg = '(^_^)∠※ 送你一束小花'

export const Toast = React.forwardRef<ToastOptions.RefAttributes, {}>((_, ref) => {
    const [tipText, setTipText] = useState(errorMsg);
    const fade = useRef(new Animated.Value(0)).current;

    const fadeAnimation = Animated.sequence([
        Animated.timing(fade, {
            toValue: 1,
            duration: 750,
            useNativeDriver: true,
            easing: Easing.linear,
        }),
        Animated.delay(3000),
        Animated.timing(fade, {
            toValue: 0,
            duration: 750,
            useNativeDriver: true,
            easing: Easing.linear,
        })
    ])

    useImperativeHandle<unknown, ToastOptions.RefAttributes>(ref, () => ({
        showToast: (content: string) => {
            setTipText(content || errorMsg)
            fadeAnimation.reset()
            fadeAnimation.start()
        },
    }))

    return (
        <Animated.View style={{ ...styles.toastContainer, opacity: fade }}>
            <View style={styles.toastTipsContainer}>
                <Text numberOfLines={5} style={{ ...styles.toastTitle, }}>{tipText} </Text>
            </View>
        </Animated.View>

    )
})

export const toastRef = React.createRef<ToastOptions.RefAttributes>();

export const showToast = (content: string) => toastRef.current?.showToast(content)



const SCREEN_WIDTH = Dimensions.get('window').width;
const styles = StyleSheet.create({
    toastContainer: {
        position: 'absolute',
        bottom: 100,
        width: '100%',
        justifyContent: 'center',
        alignItems: 'center'
    },

    toastTipsContainer: {
        position: 'absolute',
        backgroundColor: '#00000088',
        padding: 10,
        // paddingVertical: 4,
        borderRadius: 2,
        justifyContent: 'center',
        alignItems: 'center',
        minWidth: 120
    },
    toastTitle: {
        fontSize: 13,
        lineHeight: 20,
        color: 'white',
        maxWidth: SCREEN_WIDTH * 0.8
    }
})
